package com.k2data.k2app.service;

import com.k2data.app.kmx.KmxClient;
import com.k2data.app.kmx.KmxInitParams;
import com.k2data.app.kmx.cond.KmxCond;
import com.k2data.app.kmx.cond.PostDataBuilder;
import com.k2data.app.kmx.enums.KmxCondType;
import com.k2data.app.kmx.enums.KmxRestVersion;
import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.common.ResponseConstant;
import com.k2data.k2app.domain.po.JobTaskDO;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.service.pas04.Pas04ResultService;
import com.k2data.k2app.util.JsonUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 写入kmx
 * Created by clb on 17-4-18.
 */
@Log4j2
@Service
public class KmxService {

    @Autowired
    private Pas04ResultService pas04ResultService;
    @Autowired
    private JobTaskService jobTaskService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MyConstant myConstant;

    SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 推送KMX
     * @param jobTaskDO  任务对象
     * @throws Exception
     */
    public void postData(JobTaskDO jobTaskDO) throws Exception{
        KmxInitParams initParams1 = new KmxInitParams(KmxRestVersion.V040)
                .addUrl(KmxCondType.postData,myConstant.getPostdataUrl());
        // 获取接口数据
        List result =  pas04ResultService.getInterfaces(jobTaskDO.getProjectId(), jobTaskDO.getJobId(),null,null,null);
        log.debug("接口数据："+result);
        for(int i = 0;i<result.size();i++){
            // 每一行转换为一个map
            Map<String, Object> job = JsonUtils.convertJsonStrToMap(result.get(i).toString());
            // 处理time
            String ts = job.get("ts")==null?LocalDateTime.now().toString():job.get("ts").toString().replace("\"","");
            long time = 0;
            try {
                time = format.parse(ts).getTime();
            } catch (ParseException e) {
                throw new K2ResponseException(ResponseConstant.ID_NOT_FOUND,
                        String.format("%s", e.getMessage()));
            }

            JobTaskDO jobTaskDO1 = jobTaskService.getByJobId(jobTaskDO.getJobId());
            // 要插入kmx的信息
            String kmxSumField = jobTaskDO1.getTaskDO().getKmxSumField();
            String[] groupid_field = kmxSumField.split("_");

            // 要插入的fieldGroupId
            String pointId = groupid_field[0];
            Map map = deviceService.getTempplatePoint(Long.parseLong(pointId));
            String fieldGroupId = myConstant.getFieldGroup(map.get("nameEn").toString());

            // 插入的变量名
            String kmxVariable = groupid_field[1];
            Map kmxVariableMap = deviceService.getTemplateVariablesById(Long.parseLong(kmxVariable));
            String variableNameEn = kmxVariableMap.get("kmxVariableNameEn").toString();

            // 插入的变量值
            String value = job.get("analysisvalue").toString();

            // kmx同步参数初始化
            PostDataBuilder.PostBuilder postBuilder = KmxCond.postData(initParams1)
                    .post()
                    .fieldGroupId(fieldGroupId)
                    .timestamp(time);

            // kmx同步参数
            String datatype = String.valueOf(job.getOrDefault("datatype","1"));
            //channel_type=4 代表计算量
            String channelType = String.valueOf(job.getOrDefault("channel_type","4"));

            postBuilder.addField("factory_id",job.get("factory_id").toString());
            postBuilder.addField("equipment_id",job.get("equipment_id").toString());
            postBuilder.addField("machine_id",job.get("machine_id").toString());
            postBuilder.addField("datatype",datatype);//
            postBuilder.addField("channel_type",channelType);
            postBuilder.addField("channel_id",job.get("channel_id").toString());

            postBuilder.addField(variableNameEn,value);
            KmxCond kmxCond = postBuilder.build();

            KmxClient.sync(kmxCond);
        }
    }

        public boolean fieldGroupExist(String fieldGroupId) {
            KmxInitParams initParams1 = new KmxInitParams(KmxRestVersion.V040)
                    .addUrl(KmxCondType.fieldGroups, myConstant.getFieldGroupsUrl())
                    .addUrl(KmxCondType.postData,myConstant.getPostdataUrl());
            KmxCond kmxCond = KmxCond.fieldGroups(initParams1)
                    .get()
                    .id(fieldGroupId)
                    .build();
            try {
                KmxClient.sync(kmxCond);
            } catch (Exception e) {
                log.error("", e);
                return false;
            }
            return true;
        }

}
